//
//  GGAlertView.m
//  GGInternbird
//
//  Created by iOSer on 16/6/6.
//  Copyright © 2016年 耿文康. All rights reserved.
//

#import "GGAlertView.h"
#import "UILabel+LXAdd.h"
#define AlertView_W     270.0f
#define MessageMin_H    60.0f       //messagelab的最小高度
#define MessageMAX_H    120.0f      //messagelab的最大高度，当超过时，文本会以...结尾
#define LXATitleMAX_H   60.0F
#define LXATitleMin_H   20.0f
#define LXABtn_H        40.0f
#define HEXColor(hexValue,alphaValue) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:alphaValue]
#define SFQBlueColor        [UIColor colorWithRed:9/255.0 green:170/255.0 blue:238/255.0 alpha:1]
#define SFQRedColor         [UIColor colorWithRed:255/255.0 green:92/255.0 blue:79/255.0 alpha:1]
#define SFQLightGrayColor   [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1]

#define LXADTitleFont       [UIFont boldSystemFontOfSize:17];
#define LXADMessageFont     [UIFont systemFontOfSize:14];
#define LXADBtnTitleFont    [UIFont systemFontOfSize:15];
@interface GGAlertView()<UITextFieldDelegate>
@property(nonatomic,strong) UIWindow *backWindow;
@property(nonatomic,strong) UIView *alertView;
@property(nonatomic,strong) UILabel *titleLab;
@property(nonatomic,strong) UILabel *messageLab;
@property(nonatomic,strong) UIView *line;

@property(nonatomic,assign) BOOL textFieldisHidden;
@property(nonatomic,strong) UIButton *cancelBtn;
@property(nonatomic,strong) UIButton *otherBtn;
@end
@implementation GGAlertView

+ (instancetype)AlertWithTitle:(NSString *)title Text:(NSString *)text buttonTitles:(NSArray *)titles textFieldisHidden:(BOOL)textFieldisHidden delegate:(id<GGAlertViewDelegate>)delegate {
    
    return [[self alloc] initWithTitle:title Text:text buttonTitles:titles  textFieldisHidden:textFieldisHidden delegate:delegate];
}

- (instancetype)initWithTitle:(NSString *)title Text:(NSString *)text buttonTitles:(NSArray *)titles  textFieldisHidden:(BOOL)textFieldisHidden delegate:(id<GGAlertViewDelegate>)delegate{
    if (self = [super init]) {
        _textFieldisHidden = textFieldisHidden;
        _delegate = delegate;
        
        self.frame=[UIScreen mainScreen].bounds;
        self.backgroundColor=[UIColor colorWithWhite:.3 alpha:.7];
        
        _alertView=[[UIView alloc] init];
        _alertView.backgroundColor=[UIColor whiteColor];
        _alertView.layer.cornerRadius=6.0;
        _alertView.layer.masksToBounds=YES;
        _alertView.userInteractionEnabled=YES;
        CGFloat LabSpace = 25;
        if (title) {
        
            
            _titleLab=[[UILabel alloc] init];
            _titleLab.text=title;
            _titleLab.textAlignment=NSTextAlignmentCenter;
            _titleLab.textColor=[UIColor blackColor];
            _titleLab.font=LXADTitleFont;
            _titleLab.lineBreakMode=NSLineBreakByTruncatingTail;
            _titleLab.numberOfLines=0;
            _titleLab.characterSpace=2;
            _titleLab.lineSpace=3;
            CGSize labSize = [_titleLab getLableRectWithMaxWidth:AlertView_W-LabSpace*2];
            CGFloat messageLabAotuH = labSize.height < LXATitleMin_H?LXATitleMin_H:labSize.height;
            CGFloat endMessageLabH = messageLabAotuH > LXATitleMAX_H?LXATitleMAX_H:messageLabAotuH;
            _titleLab.frame=CGRectMake(LabSpace, 10, AlertView_W-LabSpace*2, endMessageLabH);
        }
        
        _messageLab=[[UILabel alloc] init];
        _messageLab.backgroundColor=[UIColor whiteColor];
        _messageLab.text=text;
        _messageLab.textColor=[UIColor lightGrayColor];
        _messageLab.font=LXADMessageFont;
        _messageLab.numberOfLines=0;
        _messageLab.textAlignment=NSTextAlignmentCenter;
        _messageLab.lineBreakMode=NSLineBreakByTruncatingTail;
        _messageLab.characterSpace=2;
        _messageLab.lineSpace=3;
        CGSize labSize = [_messageLab getLableRectWithMaxWidth:AlertView_W-LabSpace*2];
        CGFloat messageLabAotuH = labSize.height < MessageMin_H?MessageMin_H:labSize.height;
        CGFloat endMessageLabH = messageLabAotuH > MessageMAX_H?MessageMAX_H:messageLabAotuH;
        _messageLab.frame=CGRectMake(LabSpace, _titleLab.frame.size.height+_titleLab.frame.origin.y+10, AlertView_W-LabSpace*2, endMessageLabH);
        
        if (textFieldisHidden == YES) {
            _textField = [[UITextField alloc] init];
            _textField.backgroundColor = [UIColor clearColor];
            _textField.borderStyle = UITextBorderStyleNone;
            _textField.userInteractionEnabled = YES;
            //        _textField2.delegate = self;
            _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            _textField.placeholder = @"请输入昵称";
            _textField.tintColor =HEXColor(0x00cfd1, 1);
            _textField.delegate = self;
            _textField.font = [UIFont systemFontOfSize:GGRealValue(15)];
            _textField.frame = CGRectMake(LabSpace, _messageLab.frame.size.height + _messageLab.frame.origin.y + 10, AlertView_W - LabSpace*2, LXATitleMin_H);
            //计算_alertView的高度
            _alertView.frame=CGRectMake(0, 0, AlertView_W, _textField.frame.size.height+ _textField.frame.origin.y +LXABtn_H+20);
            [_alertView addSubview:_textField];
        }else{
            _alertView.frame=CGRectMake(0, 0, AlertView_W, _messageLab.frame.size.height+_messageLab.frame.origin.y+LXABtn_H+20);
        }
        
        
        _alertView.center=self.center;
        [self addSubview:_alertView];
        [_alertView addSubview:_titleLab];
        [_alertView addSubview:_messageLab];
        
        
        _line = [UIView new];
        [_line setBackgroundColor:HEXColor(0xe8ebeb, 1)];
        _line.frame = CGRectMake(0, _alertView.frame.size.height-41, _alertView.frame.size.width, 0.5);
        [_alertView addSubview:_line];
        if (titles) {
            _cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            [_cancelBtn setTitle:titles[0] forState:UIControlStateNormal];
            [_cancelBtn setTitleColor:HEXColor(0x999999, 1) forState:UIControlStateNormal];
//            [_cancelBtn setBackgroundImage:[UIImage imageWithColor:SFQLightGrayColor] forState:UIControlStateNormal];
            [_cancelBtn setBackgroundColor:[UIColor whiteColor]];
            _cancelBtn.titleLabel.font=LXADBtnTitleFont;
            _cancelBtn.layer.cornerRadius=3;
            _cancelBtn.layer.masksToBounds=YES;
            [_cancelBtn addTarget:self action:@selector(dismissAlertView) forControlEvents:UIControlEventTouchUpInside];
            [_alertView addSubview:_cancelBtn];
            
            
            
            _otherBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            [_otherBtn setTitle:titles[1] forState:UIControlStateNormal];
            [_otherBtn setTitleColor:HEXColor(0x00ced1, 1) forState:UIControlStateNormal];
            [_otherBtn setBackgroundColor:[UIColor whiteColor]];
            _otherBtn.titleLabel.font=LXADBtnTitleFont;
            _otherBtn.layer.cornerRadius=3;
            _otherBtn.layer.masksToBounds=YES;
//            [_otherBtn setBackgroundImage:[UIImage imageWithColor:SFQRedColor] forState:UIControlStateNormal];
            [_otherBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_alertView addSubview:_otherBtn];
        }
        
        
        CGFloat btnLeftSpace = 0;//btn到左边距
        CGFloat btn_y = _alertView.frame.size.height-40;
        
        _cancelBtn.tag=0;
        _otherBtn.tag=1;
        CGFloat btnSpace = 1;//两个btn之间的间距
        CGFloat btn_w =(AlertView_W/2)-btnSpace;
        
        UIView *line2 = [UIView new];
        [line2 setBackgroundColor:HEXColor(0xe8ebeb, 1)];
        line2.frame = CGRectMake(_alertView.frame.size.width-btn_w-(btnLeftSpace/2), btn_y + (LXABtn_H /4 ), 0.5, LXABtn_H /2);
        [_alertView addSubview:line2];
        _cancelBtn.frame=CGRectMake(0, btn_y, btn_w, LXABtn_H);
        _otherBtn.frame=CGRectMake(_alertView.frame.size.width-btn_w-btnLeftSpace, btn_y, btn_w, LXABtn_H);
       
       
        
    }
    
    return self;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField

{
    
    [self animateTextField: textField up: YES];
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self animateTextField: textField up: NO];
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up

{
    
    const int movementDistance = 80; // tweak as needed
    
    const float movementDuration = 0.3f; // tweak as needed
    
    
    
    int movement = (up ? -movementDistance : movementDistance);
    
    
    
    [UIView beginAnimations: @"anim" context: nil];
    
    [UIView setAnimationBeginsFromCurrentState: YES];
    
    [UIView setAnimationDuration: movementDuration];
    
    self.alertView.frame = CGRectOffset(self.alertView.frame, 0, movement);
    
    [UIView commitAnimations];
    
}

-(void)btnClick:(UIButton *)btn{
    
    
    if (self.delegate) {
        [self.delegate alertViewBtnClick:_textField.text];
    }
    [self dismissAlertView];
    
}

-(UIWindow *)backWindow{
    if (!_backWindow) {
        _backWindow=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backWindow.windowLevel=UIWindowLevelAlert;
        [_backWindow becomeKeyWindow];
        [_backWindow makeKeyAndVisible];
    }
    return _backWindow;
}

-(void)dismissAlertView{
    [self removeFromSuperview];
    [_backWindow resignKeyWindow];
    _backWindow.hidden = YES;
}

-(void)showGGAlertView{
    
    _backWindow.hidden = NO;
    [self.backWindow addSubview:self];
}


-(void)setTitleColor:(UIColor *)titleColor{
    _titleColor = titleColor;
    self.titleLab.textColor = titleColor;
}
-(void)setCancelColor:(UIColor *)cancelColor{
    _cancelColor = cancelColor;
    [self.cancelBtn setTitleColor:cancelColor forState:UIControlStateNormal];
}

-(void)setConfirmColor:(UIColor *)confirmColor{
    _confirmColor = confirmColor;
    [self.otherBtn setTitleColor:confirmColor forState:UIControlStateNormal];
}
-(void)setTextFieldPlaceholder:(NSString *)textFieldPlaceholder{
    _textFieldPlaceholder = textFieldPlaceholder;
    self.textField.placeholder = textFieldPlaceholder;
}

-(void)setMessageColor:(UIColor *)messageColor{
    _messageColor = messageColor;
    self.messageLab.textColor = messageColor;
}




@end


@implementation UIImage (Colorful)

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end
